<?php

namespace app\common\model;

use think\Model;
use traits\model\SoftDelete;

class BehaviorCategory extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'behavior_category';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    // 定义时间戳字段名
    protected $createTime = 'created_at';
    protected $updateTime = false;
    protected $deleteTime = 'deleted_at';

    const DISPLAY = 1;

    const CLASSES = 1;
    const DORM = 2;
    const DORM_STUDENT = 3;
    const STUDENT = 4;

    public static $typeList = [
        '1' => '班级',
        '2' => '宿舍',
        '3' => '宿舍学生',
        '4' => '学生',
    ];

    protected static function init()
    {
        static::beforeDelete(function ($row) {
            Behavior::destroy(['category_id' => $row->id]);
        });
    }

    public function behaviors()
    {
        return $this->hasMany(Behavior::class, 'category_id');
    }

    public static function getBehaviorData($type = [], $record_id = 0, $record_user_id = 0, $school_id = 0)
    {
        $list = BehaviorCategory::alias('category')
            ->join('__BEHAVIOR__ behavior', 'category.id = behavior.category_id and behavior.deleted_at is NULL', 'left')
            ->join('__BEHAVIOR_IMAGE__ image', 'image.id = behavior.image_id', 'left')
            ->where('category.school_id', $school_id)
            ->whereIn('category.type', $type)
            ->where('behavior.status', Behavior::NORMAL)
            ->field('behavior.id,behavior.name,behavior.category_id,behavior.type,behavior.score,behavior.image_id,category.name category_name,category.type category_type,image.url image_url')
            ->order('category.sort')
            ->select();

        if ($record_id) {
            $ret = BehaviorRecord::with(['details' => function ($query) use ($type) {
                    $query->whereIn('behavior_category_type', $type);
                }, 'images' => function ($query) use ($type) {
                    switch ($type) {
                        case [BehaviorCategory::DORM]:
                            $query->where('bed_id', 0);
                            break;
                        case [BehaviorCategory::DORM_STUDENT]:
                            $query->where('bed_id', '>', 0);
                            break;
                    }
                }])
                ->where('id', $record_id)
                ->where('record_user_id', $record_user_id)
                ->find();

            $record = [];
            if ($ret) {
                switch ($ret['behavior_category_type']) {
                    case BehaviorCategory::DORM:
                    case BehaviorCategory::DORM_STUDENT:
                        $images = [];
                        foreach ($ret['images'] as $k => $image) {
                            $images[$image['bed_id']][] = $image['url'];
                        }

                        if (!$ret['details']) {
                            $record[0]['comment'] = $ret['comment'];
                        }
                        foreach ($ret['details'] as $k => $detail) {
                            if ($detail['bed_id']) {
                                $record[$detail['bed_id']]['bed_id'] = $detail['bed_id'];
                            }
                            $record[$detail['bed_id']]['behavior_ids'][] = $detail['behavior_id'];
                            $record[$detail['bed_id']]['comment'] = BehaviorCategory::DORM == $detail['behavior_category_type'] ? $ret['comment'] : $detail['comment'];
                            if (isset($images[$detail['bed_id']])) {
                                $record[$detail['bed_id']]['images'] = $images[$detail['bed_id']];
                            }
                        }

                        break;
                    case BehaviorCategory::STUDENT:
                    case BehaviorCategory::CLASSES:
                        $images = [];
                        foreach ($ret['images'] as $k => $image) {
                            if (isset($image['record_detail_id'])) {
                                $images[$image['record_detail_id']][] =  $image['url'];
                            } else {
                                $images[$image['record_id']][] = $image['url'];
                            }
                        }

                        foreach ($ret['details'] as $k => $detail) {
                            if (isset($images[$detail['id']])) {
                                $detail['images'] = $images[$detail['id']];
                            } else {
                                $detail['images'] = [];
                            }
                            $record[$detail['behavior_id']] = $detail;
                        }
                        break;
                }
            }
        }

        //return $record;

        $data = [];
        if ($list) {
            foreach ($list as $key => $value) {
                $value['number'] = 1; // 数量默认 1
                $value['selected'] = 0; // 默认选中
                if (!strstr($value['image_url'], 'http') && strstr($value['image_url'], '/uploads')) {
                    $value['image_url'] = config('app_url') . $value['image_url'];
                }
                switch ($value['category_type']) {
                    case BehaviorCategory::DORM:
                    case BehaviorCategory::DORM_STUDENT:
                        $data['data'] = [];
                        if ($record_id && isset($record) && $record) {
                            if (BehaviorCategory::DORM == $value['category_type']) {
                                $data['data'] = current($record);
                                if (isset($data['data']['behavior_ids']) && in_array($value['id'], $data['data']['behavior_ids'])) {
                                    $value['selected'] = 1;
                                }
                            } else {
                                $data['data'] = array_values($record);
                            }
                        }

                        if (!isset($data['positive'])) {
                            $data['positive'] = [];
                        }
                        if (!isset($data['negative'])) {
                            $data['negative'] = [];
                        }
                        if ($value['type'] == Behavior::POSITIVE) {
                            $data['positive'][] = $value;
                        } else if ($value['type'] == Behavior::NEGATIVE) {
                            $data['negative'][] = $value;
                        }

                        break;
                    case BehaviorCategory::STUDENT:
                    case BehaviorCategory::CLASSES:
                        if ($record_id && isset($record) && isset($record[$value['id']])) {
                            $value['selected'] = 1;
                            $value['number'] = $record[$value['id']]['count'];
                            $value['comment'] = $record[$value['id']]['comment'];
                            $value['images'] = $record[$value['id']]['images'];
                        }
                        if (!isset($data['positive'][$value['category_id']])) {
                            $data['positive'][$value['category_id']]['id'] = $value['category_id'];
                            $data['positive'][$value['category_id']]['name'] = $value['category_name'];
                            $data['positive'][$value['category_id']]['list'] = [];
                        }
                        if (!isset($data['negative'][$value['category_id']])) {
                            $data['negative'][$value['category_id']]['id'] = $value['category_id'];
                            $data['negative'][$value['category_id']]['name'] = $value['category_name'];
                            $data['negative'][$value['category_id']]['list'] = [];
                        }
                        if ($value['type'] == Behavior::POSITIVE) {
                            $data['positive'][$value['category_id']]['list'][] = $value;
                        } else if ($value['type'] == Behavior::NEGATIVE) {
                            $data['negative'][$value['category_id']]['list'][] = $value;
                        }
                        break;
                }
            }

            foreach ($data as $key => $datum) {
                if ('positive' == $key || 'negative' == $key) {
                    $data[$key] = array_values($datum);
                }
            }
        }

        return $data;
    }

    public static function add($name, $type, $school_id, $is_deduct = 0)
    {
        $category = new BehaviorCategory();
        $category->name = $name;
        $category->type = $type;
        $category->school_id = $school_id;
        $category->is_deduct = $is_deduct;
        $category->save();

        return $category;
    }

    public function getImageAttr($value)
    {
        return !strstr($value, 'http') && strstr($value, 'uploads') ? config('app_url') . $value : $value;
    }

    /**
     * 获取 学校.行为分类.行为 便于导入查找
     *
     * @User zhenzihan
     * @Date 2020/7/6
     *
     * @param $schools
     * @param $category_type
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getMergeBehaviors($schools, $category_type)
    {
        $data = [];
        $behaviors = self::alias('category')
            ->join('__BEHAVIOR__ behavior', 'behavior.category_id = category.id')
            ->join('__BEHAVIOR_IMAGE__ image', 'image.id = behavior.image_id')
            ->whereIn('category.school_id', array_keys($schools))
            ->where('category.type', $category_type)
            ->where('category.status', BehaviorCategory::DISPLAY)
            ->where('behavior.status', Behavior::NORMAL)
            ->field('category.school_id,category.id behavior_category_id,category.name behavior_category_name,category.type behavior_category_type,behavior.id behavior_id,behavior.name behavior_name,behavior.type behavior_type,behavior.score,behavior.image_id,image.url image_url')
            ->select();

        if ($behaviors) {
            $behaviors = collection($behaviors)->toArray();
            foreach ($behaviors as $key => $behavior) {
                if (isset($schools[$behavior['school_id']])) {
                    $data["{$schools[$behavior['school_id']]}-{$behavior['behavior_category_name']}-{$behavior['behavior_name']}"] = $behavior;
                }
            }
        }

        return $data;
    }

}
